<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="128px"
      v-loading="formLoading"
    >
      <el-form-item v-if="formType === 'update'" label="配送计划编号" prop="planCode" disabled>
        <el-input v-model="formData.planCode" placeholder="请输入服务用具配送计划编号" disabled />
      </el-form-item>
      <el-form-item label="关联航班" prop="flightNo">
        <el-input v-model="formData.flightNo" placeholder="请输入关联航班" />
      </el-form-item>
      <el-form-item label="服务用具" prop="supplyId">
        <el-select
          placeholder="请选择服务用具"
          filterable
          class="!w-240px"
          v-model="formData.supplyId"
          :filter-method="getSimpleList"
        >
          <el-option
            v-for="simple in SimpleList"
            :key="simple.id"
            :label="simple.name"
            :value="simple.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务用具数量" prop="tablewareQty">
        <el-input-number
          v-model="formData.tablewareQty"
          :min="0"
          controls-position="right"
          placeholder="请输入服务用具数量(个)"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="配送状态" prop="distStatus">
        <el-select v-model="formData.distStatus" placeholder="请选择配送状态" class="!w-220px">
          <el-option
            v-for="item in getIntDictOptions(DICT_TYPE.ACM_TABLEWARE_DIST_STATUS)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配送计划时间" prop="expireDate">
        <el-date-picker
          v-model="formData.expireDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          type="textarea"
          :rows="4"
          maxlength="400"
          show-word-limit
          v-model="formData.remarks"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        @click="submitForm"
        type="primary"
        v-if="formType === 'create'"
        :disabled="formLoading"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ServiceSupplyDistPlanApi, ServiceSupplyDistPlanVO } from '@/api/acm/servicedistplan'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { OnboardSupplyApi, OnboardSupplyVO } from '@/api/acm/onboardsupply' // 补充类型定义
import { ElMessage } from 'element-plus'

/** 机供品餐具配送计划 表单 */
defineOptions({ name: 'TablewareDistPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
// 优化类型定义，确保expireDate为数组格式
const formData = ref<Partial<ServiceSupplyDistPlanVO & { expireDate: string[] }>>({
  id: undefined,
  planCode: undefined,
  flightNo: undefined,
  supplyId: undefined,
  tablewareQty: undefined,
  distStatus: undefined,
  startDate: undefined,
  endDate: undefined,
  remarks: undefined,
  expireDate: [] // 初始化日期范围为空数组
})
const formRules = reactive({
  planCode: [{ required: true, message: '服务用具配送计划编号不能为空', trigger: 'blur' }],
  flightNo: [{ required: true, message: '关联航班不能为空', trigger: 'blur' }],
  supplyId: [{ required: true, message: '服务用具不能为空', trigger: 'change' }], // 改为change触发，适配下拉框
  tablewareQty: [{ required: true, message: '服务用具数量(个)不能为空', trigger: 'blur' }],
  distStatus: [{ required: true, message: '配送状态不能为空', trigger: 'change' }],
  startDate: [{ required: true, message: '计划有效期开始不能为空', trigger: 'blur' }],
  endDate: [{ required: true, message: '计划有效期结束不能为空', trigger: 'blur' }],
  expireDate: [{ required: true, message: '配送计划时间不能为空', trigger: 'change' }] // 改为change触发，适配日期选择器
})
const formRef = ref() // 表单 Ref

// -------------------------- 核心修改：服务用具下拉框回显问题修复 --------------------------
const SimpleList = ref<OnboardSupplyVO[]>([]) // 下拉显示用服务用具列表
const allSimpleList = ref<OnboardSupplyVO[]>([]) // 完整服务用具列表（缓存所有数据）

/** 1. 加载完整服务用具列表（仅加载一次，避免重复请求） */
const loadAllSimpleList = async () => {
  // 已加载过完整列表，直接返回缓存
  if (allSimpleList.value.length > 0) return allSimpleList.value
  try {
    // 调用接口获取全量数据（保持原有参数：category=3 对应服务用具分类）
    const data = await OnboardSupplyApi.getOnboardSupplySimpleList({ category: 3, name: '' })
    allSimpleList.value = data || []
    return data
  } catch (error) {
    ElMessage.error('加载服务用具列表失败，请重试')
    allSimpleList.value = []
    return []
  }
}

/** 2. 确保已选服务用具在下拉列表中（回显补全逻辑） */
const ensureSelectedSupplyInList = async () => {
  await loadAllSimpleList()
  const selectedSupplyId = formData.value.supplyId
  if (selectedSupplyId) {
    // 检查已选服务用具是否已在显示列表中
    const isExist = SimpleList.value.some((item) => item.id === selectedSupplyId)
    if (!isExist) {
      // 从完整列表中找到对应服务用具并添加到显示列表
      const targetSupply = allSimpleList.value.find((item) => item.id === selectedSupplyId)
      if (targetSupply) SimpleList.value.push(targetSupply)
    }
  }
}

/** 3. 优化服务用具过滤方法：合并已选数据与过滤结果 */
const getSimpleList = async (query?: string) => {
  // 确保先加载完整服务用具列表
  await loadAllSimpleList()

  // 步骤1：提取已选服务用具（避免回显数据丢失）
  const selectedSupplies: OnboardSupplyVO[] = []
  const selectedSupplyId = formData.value.supplyId
  if (selectedSupplyId) {
    const targetSupply = allSimpleList.value.find((item) => item.id === selectedSupplyId)
    if (targetSupply) selectedSupplies.push(targetSupply)
  }

  // 步骤2：根据查询条件过滤数据（保持首屏200条性能优化）
  let filteredSupplies: OnboardSupplyVO[] = []
  if (!query) {
    // 无查询时：取完整列表前200条
    filteredSupplies = [...allSimpleList.value].slice(0, 200)
  } else {
    // 有查询时：按服务用具名称模糊匹配（不区分大小写）
    filteredSupplies = allSimpleList.value.filter((supply) =>
      supply.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 步骤3：合并已选数据与过滤结果，通过Map去重（避免重复选项）
  SimpleList.value = Array.from(
    new Map([...selectedSupplies, ...filteredSupplies].map((item) => [item.id, item])).values()
  )
  return SimpleList.value
}
// -----------------------------------------------------------------------------------

/** 打开弹窗（修改：加载完整数据并补全回显） */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 先加载完整服务用具列表，再初始化下拉显示列表
  await Promise.all([loadAllSimpleList(), getSimpleList()])

  // 修改场景：加载配送计划数据并补全服务用具回显
  if (id) {
    formLoading.value = true
    try {
      const planData = await ServiceSupplyDistPlanApi.getTablewareDistPlan(id)
      formData.value = { ...planData }
      // 处理日期范围回显（确保格式适配日期选择器）
      if (planData.startDate && planData.endDate) {
        formData.value.expireDate = [planData.startDate, planData.endDate]
      } else {
        formData.value.expireDate = []
      }
      // 关键：补全已选服务用具到下拉列表
      await ensureSelectedSupplyInList()
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单（原有逻辑保留，优化日期参数处理） */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 处理日期范围：将日期选择器的数组拆分为 startDate 和 endDate（适配接口要求）
  if (formData.value.expireDate && formData.value.expireDate.length === 2) {
    formData.value.startDate = formData.value.expireDate[0]
    formData.value.endDate = formData.value.expireDate[1]
  }

  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const submitData = formData.value as unknown as ServiceSupplyDistPlanVO
    if (formType.value === 'create') {
      await ServiceSupplyDistPlanApi.createTablewareDistPlan(submitData)
      message.success(t('common.createSuccess'))
    } else {
      await ServiceSupplyDistPlanApi.updateTablewareDistPlan(submitData)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success') // 通知父组件刷新数据
  } finally {
    formLoading.value = false
  }
}

/** 重置表单（原有逻辑保留，补充expireDate初始化） */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planCode: undefined,
    flightNo: undefined,
    supplyId: undefined,
    tablewareQty: undefined,
    distStatus: undefined,
    startDate: undefined,
    endDate: undefined,
    remarks: undefined,
    expireDate: [] // 重置时保持日期范围为空数组
  }
  formRef.value?.resetFields()
}
</script>